package com.wyl.auth.captcha;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import com.wyl.auth.captcha.constant.CaptchaConst;
import com.wyl.auth.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @Description
 * @Author WuYiLong
 * @Date 2025/4/12 13:41
 */
@Service
public class CaptchaServiceImpl implements CaptchaService {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public String generateCaptcha() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 36, 4, 10);
        String base64Img = CaptchaConst.BASE64_PREFIX + lineCaptcha.getImageBase64();
        String code = lineCaptcha.getCode();
        if(StrUtil.isNotBlank(code)){
            redisTemplate.opsForValue().set(CaptchaConst.CODE, code.toLowerCase());
        }
        return base64Img;
    }

    @Override
    public boolean validateCaptcha(String code) {
        String originCode = redisTemplate.opsForValue().get(CaptchaConst.CODE);
        if(code.toLowerCase().equals(originCode)) {
           return true;
        }
        return false;
    }
}